package com.cloud.logger.zchain.zchainserver.service;

import com.alibaba.fastjson.JSON;
import com.cloud.logger.zchain.core.common.util.DateUtil;
import com.cloud.logger.zchain.zchainserver.entity.AngelaLogger;
import com.cloud.logger.zchain.zchainserver.entity.AngelaLoggerProject;
import com.cloud.logger.zchain.zchainserver.entity.AngelaLoggerProjectEveryDay;
import com.cloud.logger.zchain.zchainserver.entity.vo.AngelaLoggerProjectBugVo;
import com.cloud.logger.zchain.zchainserver.entity.vo.AxisSeriesNode;
import com.cloud.logger.zchain.zchainserver.entity.vo.AxisVo;
import com.cloud.logger.zchain.zchainserver.mongo.AngelaEntityRepository;
import com.cloud.logger.zchain.zchainserver.mongo.AngelaProjectRepository;
import com.cloud.logger.zchain.zchainserver.mongo.AngelaProjectWeekRepository;
import com.mongodb.WriteResult;
import org.springframework.beans.BeanUtils;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * User: zhengyt
 * Date: 2017/11/7
 * Time: 14:13
 */
@Service
public class AngelaPjMonthAdWeekService {

    @Resource
    private AngelaEntityRepository angelaEntityRepository;
    @Resource
    private AngelaProjectWeekRepository angelaProjectWeekRepository;
    @Resource
    private AngelaProjectRepository angelaProjectRepository;
    @Resource
    private MongoTemplate mongoTemplate;

    //周和月日志统计的常量
    static String WEEK = "week";
    static String MONTH = "month";
    //时间月日格式
    private static String MONTH_AND_DAY = "MM-dd";

    private static String CREATED_DATE ="createdDate";

    private static String CREATE_TIME ="createTime";

    private static String DATE_LIMIT_HH = "yyyy-MM-dd HH";

    public void saveLoggerAdBugTimer() {


        Date beginDate = new Date();
        Calendar date = Calendar.getInstance();
        date.setTime(beginDate);
        date.set(Calendar.DATE, date.get(Calendar.DATE) - 1);
        Date startTime = DateUtil.getDayStart(date.getTime());
        Date endTime = DateUtil.getDayEnd(date.getTime());

        //查询除了父节点等于-1的项目名称
        List<AngelaLoggerProject> angelaLoggerProjects = angelaProjectRepository.findByParentNodeNot("-1");
        for(AngelaLoggerProject log : angelaLoggerProjects){
            //查询昨天错误日志和全部日志数
            long errorLoggers = angelaEntityRepository.countByProjectAndCreateTimeBetweenAndAlarmLevelNot(log.getCode(),
                    startTime,  endTime, 0);
            long loggers = angelaEntityRepository.countByProjectAndCreateTimeBetween(log.getCode(),
                    startTime,  endTime);

            AngelaLoggerProjectEveryDay angelaLoggerProjectEveryDay  = new AngelaLoggerProjectEveryDay();
            angelaLoggerProjectEveryDay.setErrorLogger((int)errorLoggers);
            angelaLoggerProjectEveryDay.setLogger((int)loggers);
            angelaLoggerProjectEveryDay.setCreatedDate(new Date());
            angelaLoggerProjectEveryDay.setBugCreateTime(startTime);
            angelaLoggerProjectEveryDay.setProject(log.getCode());
            //保存信息到数据库
            angelaProjectWeekRepository.save(angelaLoggerProjectEveryDay);
            if (angelaLoggerProjectEveryDay.getId() !=null){
                System.out.println("保存成功!");
            }else{
                System.out.println("保存失败!"+log.toString());
            }
        }

    }


    /**
     * 查询一周或一月bug数
     * @param id
     * @param type
     * @return
     * @throws Exception
     */
    public AxisVo findLastWeekOrMonthBugs(String id, String type) throws Exception {
        AngelaLoggerProject project = angelaProjectRepository.findOne(id);
        if(project==null)
            throw new Exception("");
        AxisVo axisVo = new AxisVo("个");
        List xAxis = new ArrayList<>();
        List series = new ArrayList<>();
        List seriesBugs = new ArrayList<>();
        List seriesLogs = new ArrayList<>();
        //vo赋值
        AngelaLoggerProjectBugVo vo = new AngelaLoggerProjectBugVo();
        BeanUtils.copyProperties(project, vo);
        Date startTime = new Date();
        Date endTime = new Date();

        Calendar dateStart = Calendar.getInstance();
        Calendar dateEnd = Calendar.getInstance();
        dateStart.setTime(startTime);
        dateEnd.setTime(endTime);

        //根据类型是周和月设置开始日期
        if(WEEK.equals(type)){
            dateStart.set(Calendar.DATE, dateStart.get(Calendar.DATE) - 7);
        }else if(MONTH.equals(type)){
            dateStart.set(Calendar.DATE, dateStart.get(Calendar.DATE) - 31);
        }

        startTime = DateUtil.getDayStart(dateStart.getTime());
        startTime = DateUtil.addSecond(startTime,-2);
        System.out.println(DateUtil.format(startTime));

        dateEnd.set(Calendar.DATE, dateEnd.get(Calendar.DATE) - 1);
        endTime = DateUtil.getDayEnd(dateEnd.getTime());
        System.out.println(DateUtil.format(endTime));

        List<AngelaLoggerProjectEveryDay> weekLoggersList = angelaProjectWeekRepository.findByProjectAndBugCreateTimeBetween(project.getCode(),
                startTime,  endTime);
        System.out.println(JSON.toJSON(weekLoggersList));
        //遍历获取每天的日志数量
        for(AngelaLoggerProjectEveryDay logger : weekLoggersList){
            seriesBugs.add(logger.getErrorLogger());
            seriesLogs.add(logger.getLogger());
            if(logger.getBugCreateTime()!=null){
                xAxis.add(DateUtil.format(logger.getBugCreateTime(),MONTH_AND_DAY));
            }

        }

        AxisSeriesNode bugNode = new AxisSeriesNode("bug数", "line");
        bugNode.setData(seriesBugs);
        series.add(bugNode);
        AxisSeriesNode totoalNode = new AxisSeriesNode("总数", "line");
        totoalNode.setData(seriesLogs);
        series.add(totoalNode);
        axisVo.setXaxis(xAxis);
        axisVo.setSeries(series);

        return axisVo;
    }

    public AxisVo findTodayBugs(String id) throws Exception {
        AngelaLoggerProject project = angelaProjectRepository.findOne(id);

        if(project==null)
            throw new Exception("");

        AxisVo axisVo = new AxisVo("个");

        List xAxis = new ArrayList<>();
        List series = new ArrayList<>();
        List seriesBugs = new ArrayList<>();
        List seriesLogs = new ArrayList<>();
        //vo赋值
        AngelaLoggerProjectBugVo vo = new AngelaLoggerProjectBugVo();
        BeanUtils.copyProperties(project, vo);

        String startTime;
        String endTime;
        int hour;
        for(int i=23;i>=0;i--){
            Calendar calendar = Calendar.getInstance();
            hour =calendar.get(Calendar.HOUR_OF_DAY)-i;

            //从一点开始计算bug数目
            if((calendar.get(Calendar.HOUR_OF_DAY)-i)<1)
                continue;

            xAxis.add(hour);
            calendar.set(Calendar.HOUR_OF_DAY, hour);
            SimpleDateFormat df = new SimpleDateFormat(DATE_LIMIT_HH);
            //小时的结束时间
            endTime = df.format(calendar.getTime())+":00:00";
            ;
            calendar.set(Calendar.HOUR_OF_DAY, hour-1);
            //查询小时bug的开始时间
            startTime = df.format(calendar.getTime())+":00:00";
            long hourErrorBugs= angelaEntityRepository.countByProjectAndCreateTimeBetweenAndAlarmLevelNot(project.getCode(),
                    DateUtil.parse(startTime, DateUtil.YMD_DASH_WITH_TIME), DateUtil.parse(endTime, DateUtil.YMD_DASH_WITH_TIME),0);

            long hourLoggers= angelaEntityRepository.countByProjectAndCreateTimeBetween(project.getCode(),
                    DateUtil.parse(startTime, DateUtil.YMD_DASH_WITH_TIME), DateUtil.parse(endTime, DateUtil.YMD_DASH_WITH_TIME));

            seriesBugs.add(hourErrorBugs);
            seriesLogs.add(hourLoggers);
        }

        AxisSeriesNode bugNode = new AxisSeriesNode("bug数", "line");
        bugNode.setData(seriesBugs);
        series.add(bugNode);
        AxisSeriesNode totoalNode = new AxisSeriesNode("总数", "line");
        totoalNode.setData(seriesLogs);
        series.add(totoalNode);
        axisVo.setXaxis(xAxis);
        axisVo.setSeries(series);

        return axisVo;
    }


    public void deleteLogMonthAgo(){
        Date startTime = new Date();
        Calendar dateStart = Calendar.getInstance();
        dateStart.setTime(startTime);

        //根据类型是周和月设置开始日期
        dateStart.set(Calendar.DATE, dateStart.get(Calendar.DATE) - 31);
        startTime = DateUtil.getDayStart(dateStart.getTime());

        Query query = new Query();
        Criteria criteria = Criteria.where(CREATE_TIME).lt(DateUtil.format(startTime));
        query.addCriteria(criteria);
        WriteResult result = mongoTemplate.remove(query, AngelaLogger.class);
        if(result.getN() >0 ){
            System.out.println("删除成功!");
        }else{
            System.out.println("没有删除日志!");
        }

    }


}
